﻿using System;
using System.Web.Mvc;

namespace GetIPAddress.Backend.Controllers
{
    public class HomeController : Controller
    {
        // GET: Home
        public ActionResult Index()
        {
            ViewBag.ClientIPAddress = GetClientIPAddress();
            return View();
        }

        private string GetClientIPAddress()
        {
            string clientIPAddress = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];

            if (String.IsNullOrEmpty(clientIPAddress))
                clientIPAddress = Request.ServerVariables["REMOTE_ADDR"];

            if (String.IsNullOrEmpty(clientIPAddress))
                clientIPAddress = Request.UserHostAddress;

            if (String.IsNullOrEmpty(clientIPAddress) || clientIPAddress.Trim() == "::1")
                clientIPAddress = "Unknown";

            try
            {
                clientIPAddress = clientIPAddress.Remove(clientIPAddress.IndexOf(':'));
            }
            catch { }

            return clientIPAddress;
        }
    }
}